package com.yhn.minio;

import io.minio.*;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Component
public class MinioUtils {
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private MinioClient minioClient;

    public String uploadFile(String objectName, InputStream inputStream, long size, String contentType) throws Exception {
        ensureBucketExists();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(objectName)
                .stream(inputStream, size, -1)
                .contentType(contentType)
                .build();
        minioClient.putObject(args);
        return objectName;
    }

    public String uploadFile(MultipartFile file, String objectName) throws Exception {
        ensureBucketExists();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(args);
        return objectName;
    }

    public String getPresignedUrl(String objectName) throws Exception {
        minioClient.statObject(StatObjectArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(objectName)
                .build());
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(minioConfig.getBucket())
                        .object(objectName)
                        .expiry(minioConfig.getExpireMinutes(), TimeUnit.MINUTES)
                        .build());
    }

    private void ensureBucketExists() throws Exception {
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucket()).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucket()).build());
        }
    }
}


